package com.dataseek.iot.toolkit.tenant.config;

import com.dataseek.iot.toolkit.tenant.datasource.DynamicDataSource;
import com.dataseek.iot.toolkit.tenant.entity.SysTenant;
import com.dataseek.iot.toolkit.tenant.service.SysTenantService;
import com.dataseek.iot.toolkit.tenant.utils.CustomDBUtils;
import com.dataseek.iot.toolkit.tenant.utils.SpringContextUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源初始化
 *
 * @author 李嘉
 * @version 1.0
 * @Description 动态数据源初始化
 * @date 2020/5/19 00:08
 */
@Slf4j
@Configuration
@Order(value = 2)
public class DynamicDataSourceInit {
    @Autowired
    private SysTenantService sysTenantService;

    @Bean
    public void initDataSource() {
        log.info("======初始化动态数据源=====");
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        HikariDataSource master = (HikariDataSource) SpringContextUtils.getBean("master");
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);
        List<SysTenant> sysTenantList = sysTenantService.list();
        for(SysTenant sysTenant:sysTenantList){
            HikariDataSource dataSource = new HikariDataSource();
            String companyCode = sysTenant.getCompanyCode();
            String dbType = sysTenant.getDbType();
            String dbHost = sysTenant.getDbHost();
            Integer dbPort = sysTenant.getDbPort();
            String databaseName = sysTenant.getDatabaseName();
            String schemaName = sysTenant.getSchemaName();
            String driverName = sysTenant.getDriverName();
            String userName = sysTenant.getSuperAdminName();
            String password = sysTenant.getSuperAdminPassword();
            dataSource.setDriverClassName(driverName);
            dataSource.setJdbcUrl(CustomDBUtils.generateJdbcUrl(dbType,dbHost,dbPort,databaseName,schemaName));
            dataSource.setUsername(userName);
            dataSource.setPassword(password);
            dataSource.setDataSourceProperties(master.getDataSourceProperties());
            //String datasourceKey =companyCode+"-"+dbType+"-db";
            String datasourceKey =companyCode;
            dataSourceMap.put(datasourceKey,dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
         */
        dynamicDataSource.afterPropertiesSet();
    }
}
